<template>
	<div class="income">
		<div>
			<div style="display: flex;justify-content: space-between;">
				<div>
					<el-date-picker v-model="selectDate" :type="dateType" placeholder="选择日期" 
						@change="changeDate" :clearable="false" style="width: 140px;" size="mini">
					</el-date-picker>
					<el-select v-model="dateType" style="width: 80px;" @change="changeType" size="mini">
						<el-option value="year" label="年"></el-option>
						<el-option value="month" label="月"></el-option>
						<el-option value="date" label="日"></el-option>
					</el-select>
				</div>
				<div>
					<el-button @click="exportExcel" plain size="mini" v-debounce>
						导出
					</el-button>
					<el-button size="mini" @click="reset" v-debounce>重置</el-button>
				</div>
			</div>
			<!-- 条件查询 -->
			<div style="display: flex;justify-content: space-between;">
				<div>
					<el-select v-model="accountId" filterable remote clearable size="mini"
						:loading="accountLoading" placeholder="按账户搜索"
						@change="onSubmit" :remote-method="getAccountList"
						@focus="getAccountList('')" style="width: 220px;">
						<el-option v-for="item in accountList" :key="item.id" 
							:label="item.account" :value="item.id">
						</el-option>
					</el-select>
				</div>
				<div>
					<el-select v-model="payee" filterable remote clearable size="mini"
						:loading="selectLoading" :remote-method="getSelectList"
						placeholder="按收款方搜索" style="width: 250px;"
						@change="onSubmit" @focus="getSelectList('')" >
						<el-option v-for="item in selectList" :key="item.value" 
							:label="item.label" :value="item.value">
						</el-option>
					</el-select>
					<el-select v-model="payeeType" placeholder="收款方类型" size="mini"
						@change="onSubmit" style="width: 100px;">
						<el-option label="全部" :value="null"></el-option>
						<el-option label="员工" :value="0"></el-option>
						<el-option label="供应商" :value="1"></el-option>
					</el-select>
				</div>
			</div>
		</div>
		<div class="data-table">
			<el-table :data="tableData" v-loading="loading" border stripe
				style="width: 100%" height="100%">
				<el-table-column prop="i" label="序号" width="50" fixed="left">
				</el-table-column>
				<el-table-column prop="payee" label="收款方" width="200">
				</el-table-column>
				<el-table-column prop="amountPayable" label="付款金额" width="80">
				</el-table-column>
				<el-table-column prop="datePayable" label="付款日期" width="100">
				</el-table-column>
				<el-table-column prop="paymentAmount" label="实付金额" width="80">
				</el-table-column>
				<el-table-column prop="paymentDate" label="实付日期" width="170">
				</el-table-column>
				<el-table-column prop="account" label="付款账户" width="220">
				</el-table-column>
			</el-table>
			<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="currentPage" :page-sizes="[20, 50, 100]" :page-size="pageSize"
				layout="total, sizes, prev, pager, next, jumper" :total="total">
			</el-pagination>
		</div>
	</div>
</template>

<script>
	import warehouseApi from "../../api/warehouse.js";
	import userApi from "../../api/user.js"
	import financeApi from "../../api/financeManage.js";
	export default {
		data() {
			return {
				userInfo: {},
				tableData: [],
				loading: false,
				currentPage: 1,
				pageSize: 50,
				total: 0,
				payee: null,
				payeeType: null,
				selectList: [],
				selectLoading: false,
				year: null,
				yearMonth: null,
				yearMonthDay: null,
				selectDate: null,
				dateType: "month",
				totalAmount: null,
				accountId: null,
				accountList: [],
				accountLoading: false,
				radio: 0,
			};
		},
		created() {
			this.userInfo = JSON.parse(localStorage.getItem("userInfo"))
			this.initializeDate();
			this.getBillingList();
		},
		methods:{
			initializeDate() {
				const currentYear = new Date().getFullYear();
				let currentMonth = new Date().getMonth() + 1;
				let currentDay = new Date().getDate()
				currentMonth = currentMonth < 10 ? '0' + currentMonth : currentMonth;
				currentDay = currentDay < 10 ? '0' + currentDay : currentDay;
				this.yearMonth = `${currentYear}-${currentMonth}`
				this.selectDate = this.yearMonth;
			},
			// 获取账单列表
			getBillingList(){
				this.loading = true
				const data = {
					payee: this.payee,
					payeeType: this.payeeType,
					year: this.year,
					yearMonth: this.yearMonth,
					yearMonthDay: this.yearMonthDay,
					account: this.accountId,
					currentPage: this.currentPage,
					pageSize: this.pageSize,
				}
				financeApi.getPaymentBillingList(data).then(res =>{
					if (res.code === 200){
						this.total = res.data.total
						this.tableData = res.data.paymentBillingList.map((item,index) =>{
								item.i = (this.currentPage - 1) * this.pageSize + index + 1;
								return item;
							})
					}
				}).finally(() =>{
					this.loading = false
				})
			},
			// pageSize变化
			handleSizeChange(pageSize) {
				this.pageSize = pageSize
				this.getBillingList()
			},
			// 页码变化
			handleCurrentChange(curPage) {
				this.currentPage = curPage
				this.getBillingList()
			},
			// 日期类型改变
			changeType(){
				this.selectDate = new Date();
				this.changeDate();
			},
			// 日期改变
			changeDate() {
				//console.log("选择的日期==>",this.selectDate)
				this.year = null;
				this.yearMonth = null;
				this.yearMonthDay = null;
				if (this.selectDate !== null) {
					const year = this.selectDate.getFullYear();
					const month = this.selectDate.getMonth() + 1; // 月份从 0 开始，需要加 1
					const day = this.selectDate.getDate();
					// 格式化月份和日期，确保始终是两位数
					const formattedMonth = month < 10 ? '0' + month : month;
					const formattedDay = day < 10 ? '0' + day : day;
					if (this.dateType === "year") {
						this.year = year;
					} else if (this.dateType === "month"){
						this.yearMonth = `${year}-${formattedMonth}`;
					}else {
						this.yearMonthDay = `${year}-${formattedMonth}-${formattedDay}`;
					}
				}
				this.onSubmit();
			},
			// 条件查询提交
			onSubmit() {
				this.currentPage = 1
				this.pageSize = 50
				this.getBillingList()
			},
			// 远程搜索收款方
			getSelectList(query) {
				this.selectLoading = true;
				if (this.payeeType === 0){
					// 员工
					const data = {
						nickName: query
					}
					userApi.fuzzyQuery(data).then(res => {
						if (res.code === 200) {
							this.selectList = res.data.userVoList.map(item =>{
								const data = {
									label: item.nickName,
									value: item.id,
								}
								return data;
							});
						}
					}).finally(() =>{
						this.selectLoading = false;
					})
				}else if (this.payeeType === 1){
					// 供应商
					const data = {
						suppliersName: query,
						currentPage: 1,
						pageSize: 50
					}
					warehouseApi.getSuppliersList(data).then(res =>{
						if (res.code === 200) {
							this.selectList = res.data.suppliersVoList.map(item =>{
								const data = {
									label: item.suppliersName,
									value: item.id,
								}
								return data;
							});
						}
					}).finally(() =>{
						this.selectLoading = false;
					})
				}else {
					this.$message.error("请先选择类型");
					this.selectLoading = false;
					return;
				}
			},
			// 远程搜索账户
			getAccountList(query){
				this.accountLoading = true;
				const data = {
					accountName: query,
					currentPage: 1,
					pageSize: 10,
				}
				financeApi.getAccountList(data).then(res =>{
					if (res.code === 200){
						this.accountList = res.data.accountList
					}
				}).finally(() =>{
					this.accountLoading = false;
				})
			},
			// 重置查询条件
			reset() {
				this.payee = null
				this.payeeType = null
				this.dateType = "month"
				this.currentPage = 1
				this.accountId = null
				this.changeType();
			},
			//导出Excel
			exportExcel() {
				const data = this.formatData(this.tableData); // 将数据格式化为xlsx可以识别的格式
				const wb = this.$XLSX.utils.book_new();
				const ws = this.$XLSX.utils.json_to_sheet(data);
				// 设置列宽
				const columnWidths = [
					{wch: 5}, // 序号
					{wch: 25}, // 收款方
					{wch: 10}, // 付款金额
					{wch: 15}, // 付款日期
					{wch: 10}, // 实付金额
					{wch: 20}, // 实付日期
					{wch: 25} // 付款账户
				];
				ws['!cols'] = columnWidths;
				this.$XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
				let fileName = "支出明细";
				if (this.dateType === "year"){
					fileName = this.year+"支出明细";
				}else if (this.dateType === "month"){
					fileName = this.yearMonth+"支出明细";
				}else {
					fileName = this.yearMonthDay+"支出明细";
				}
				this.$XLSX.writeFile(wb, fileName+".xlsx");
			},
			formatData(data) {
				// 格式化表格数据，将对象数组转换为数组对象
				return data.map((item) => {
					const {
						i,
						payee,
						amountPayable,
						datePayable,
						paymentAmount,
						paymentDate,
						account
					} = item;
					return {
						序号: i,
						收款方: payee,
						付款金额: amountPayable,
						付款日期: datePayable,
						实付金额: paymentAmount,
						实付日期: paymentDate,
						付款账户: account,
					};
				});
			},
		}
	}
</script>

<style>
	.income {
		height: 100%;
	}
	
	.data-table{
		height: 94%;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		justify-content: center;
		margin-top: 10px;
	}
</style>